#
#		Author: Alexandros Sigalas
#
#      This program is free software; you can redistribute it and/or modify
#      it under the terms of the GNU General Public License as published by
#      the Free Software Foundation; either version 2 of the License, or
#      (at your option) any later version.
#      
#      This program is distributed in the hope that it will be useful,
#      but WITHOUT ANY WARRANTY; without even the implied warranty of
#      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#      GNU General Public License for more details.
#      
#      You should have received a copy of the GNU General Public License
#      along with this program; if not, write to the Free Software
#      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#      MA 02110-1301, USA.


Units= ["km","m","cm","mm","inch"]
layerModes= {"byMaterial":1, "byFillColor":2, "byLineColor":3, "byLineWeight":4, "singleLayer":5 }

class Drawing(object):
	__slots__=("polygons", "scale", "materials", "width", "height", "layers", "layer_mode", "units")
	def __init__(self, polygons=[], scale=1.0, width=None, height=None, units="m"):
		self.polygons = polygons
		self.scale = scale
		self.width = width
		self.height = height
		self.unit = units
		self.layers = list()
		self.layer = None

	def makeLayers(self, mode=layerModes["singleLayer"]):
		'''Modes: "singleLayer", "byMaterial", "byLineWeight", "byLineColor", "byFillColor" '''
		#TODO: fix layermodes
		if not mode in layerModes:
			mode= layerModes["singleLayer"]
		self.layerMode = mode
		layers = dict()
		for pl in self.polygons:
			mat = pl.getMaterial()

			if mode is None:
				lname = "Drawing"
			elif mode == "byMaterial":
				lname = mat.name
			elif mode == "byLineweight":
				lname = str(round(mat.line_weight,3))
			elif mode == "byLinecolor":
				c= col2RGB(mat.line_color)
				lname = "rgb_"+str(c[0])+"_"+str(c[1])+"_"+str(c[2])
			elif mode == "byFillcolor":
				c= col2RGB(mat.fill_color)
				lname = "rgb_"+str(c[0])+"_"+str(c[1])+"_"+str(c[2])

			if lname not in layers:
				layers[lname] = [pl]
			else:
				layers[lname].append(pl)

		for L in layers:
			layers[L].sort(key=lambda x: (x.getMaterial().alpha))

		self.layers  = [(layername,layer) for layername,layer in layers.iteritems()]
		if mode == "byMaterial":
			#for proper export in svg format (and others supporting transparency), transparent layers must be after ones with opaque polys
			self.layers.sort(key=lambda x:(x[1][0].getMaterial().alpha))
			#TODO: fix other modes? (i think not possible)

